package weaver.interfaces.gangwan.cronjob;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @Title ecology-9
 * @Company 泛微软件
 * @CreateDate 2025/6/25
 * @Description 同步考勤机组织
 * @Author AdminZm
 */
public class SyncKqjOrgDataJob extends BaseCronJob {

    BaseBean baseBean = new BaseBean();

    @Override
    public void execute() {
        baseBean.writeLog("SyncKqjOrgDataJob start.");
        try {
            String url = baseBean.getPropValue("gangwan_zm_prop", "kqj_url");
            String token = baseBean.getPropValue("gangwan_zm_prop", "kqj_token");
            String fbId = baseBean.getPropValue("gangwan_zm_prop", "subcontracting_staff_fbid");
            if (StringUtils.isEmpty(url) || StringUtils.isEmpty(token) || StringUtils.isEmpty(fbId)) {
                baseBean.writeLog("SyncKqjOrgDataJob prop value is null.");
                return;
            }
            /*Gson gson = new Gson();
            Type type = new TypeToken<Map<String, Object>>() {}.getType();

            // 获取考勤机部门列表信息
            List<Map<String, Object>> kqjOrgInfoMapList = new ArrayList<>();
            int pageSize = 2000;
            String deptUrl = url + "api/department/getDepartmentList?access_token=" + token + "&&pageSize=" + pageSize;
            int pageNo = 1;
            boolean isGoing = true;
            while (isGoing) {
                String deptUrlNew = deptUrl + "&pageNo=" + pageNo;
                String result = HttpRequest.post(deptUrlNew)
                        .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                        .timeout(20000)
                        .execute().body();

                if (StringUtils.isEmpty(result)) {
                    baseBean.writeLog("SyncKqjOrgDataJob result is null.");
                    return;
                }
                baseBean.writeLog("SyncKqjOrgDataJob result is:" + result);
                Map<String, Object> resultMap = gson.fromJson(result, type);
                Object message = resultMap.get("message");
                if (message == null || !StringUtils.equals(message.toString(), "success")) {
                    baseBean.writeLog("SyncKqjOrgDataJob message is not success.");
                    return;
                }
                Object data = resultMap.get("data");
                if (data == null) {
                    baseBean.writeLog("SyncKqjOrgDataJob data is null.");
                    return;
                }
                Map<String, Object> dataMap = (Map<String, Object>) data;
                if (CollectionUtils.isEmpty(dataMap)) {
                    baseBean.writeLog("SyncKqjOrgDataJob dataMap is null.");
                    return;
                }
                Object total = dataMap.get("total");
                if (total == null) {
                    baseBean.writeLog("SyncKqjOrgDataJob total is null.");
                    return;
                }
                int count = pageSize * pageNo;
                if (new BigDecimal(total.toString()).compareTo(new BigDecimal(String.valueOf(count))) > 0) {
                    pageNo = pageNo + 1;
                } else {
                    isGoing = false;
                }
                Object dataSon = dataMap.get("data");
                if (dataSon == null) {
                    baseBean.writeLog("SyncKqjOrgDataJob dataSon is null.");
                    return;
                }
                List<Map<String, Object>> dataSonMap = (List<Map<String, Object>>) dataSon;
                if (!CollectionUtils.isEmpty(dataSonMap)) {
                    kqjOrgInfoMapList.addAll(dataSonMap);
                }
            }

            if (CollectionUtils.isEmpty(kqjOrgInfoMapList)) {
                baseBean.writeLog("SyncKqjOrgDataJob kqjOrgInfoMapList is null.");
                return;
            }
            Map<String, Map<String, Object>> kqjOrgMapMap = new HashMap<>();
            Map<String, Set<String>> kqjOrgXjSetMap = new HashMap<>();
            Set<String> yjBmKqjSet = new HashSet<>();
            for (Map<String, Object> kqjOrgInfo : kqjOrgInfoMapList) {
                Object code = kqjOrgInfo.get("code");
                Object parentCode = kqjOrgInfo.get("parentCode");
                if (code == null) {
                    continue;
                }
                if (parentCode == null) {
                    yjBmKqjSet.add(code.toString());
                } else {
                    Set<String> xjBmSet = new HashSet<>();
                    if ((!CollectionUtils.isEmpty(kqjOrgXjSetMap)) && kqjOrgXjSetMap.containsKey(parentCode.toString())) {
                        xjBmSet = kqjOrgXjSetMap.get(parentCode.toString());
                    }
                    xjBmSet.add(code.toString());
                    kqjOrgXjSetMap.put(parentCode.toString(), xjBmSet);
                }
                kqjOrgMapMap.put(code.toString(), kqjOrgInfo);
            }*/

            String addUrl = url + "api/department/add?access_token=" + token;
            String deleteUrl = url + "api/department/delete/";

            // 获取OA"分包人员分部"下所有部门
            Map<String, Map<String, String>> oaOrgInfoMap = new HashMap<>();
            RecordSet rs = new RecordSet();
            rs.execute("SELECT id, departmentmark, supdepid, canceled, showorder FROM hrmdepartment where subcompanyid1 = " + fbId);
            while (rs.next()) {
                String id = rs.getString("id");
                String departmentmark = rs.getString("departmentmark");
                String supdepid = rs.getString("supdepid");
                String canceled = rs.getString("canceled");
                String showorder = rs.getString("showorder");
                if (StringUtils.isEmpty(id) || StringUtils.isEmpty(departmentmark)) {
                    continue;
                }
                if (StringUtils.isEmpty(showorder)) {
                    showorder = "0";
                }
                Map<String, String> oaOrgInfo = new HashMap<>();
                oaOrgInfo.put("id", id);
                oaOrgInfo.put("departmentmark", departmentmark);
                oaOrgInfo.put("supdepid", supdepid);
                oaOrgInfo.put("canceled", canceled);
                oaOrgInfo.put("showorder", showorder);
                oaOrgInfoMap.put(id, oaOrgInfo);
            }

            if (CollectionUtils.isEmpty(oaOrgInfoMap)) {
                baseBean.writeLog("SyncKqjOrgDataJob oaOrgInfoMap is null.");
                return;
            }

            Set<String> addIdSet = new HashSet<>();
            Set<String> deleteIdSet = new HashSet<>();
            for (Map.Entry<String, Map<String, String>> entry : oaOrgInfoMap.entrySet()) {
                String key = entry.getKey();
                Map<String, String> value = entry.getValue();
                if (StringUtils.isEmpty(key) || CollectionUtils.isEmpty(value)) {
                    continue;
                }
                String canceled = value.get("canceled");
                boolean isCanceled = StringUtils.isNotEmpty(canceled) && StringUtils.equals(canceled, "1");
                if (isCanceled) {
                    if (CollectionUtils.isEmpty(deleteIdSet) || !deleteIdSet.contains(key)) {
                        String deleteUrlTemp = deleteUrl + key + "?access_token=" + token;
                        String result = HttpRequest.post(deleteUrlTemp)
                                .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                                .timeout(20000)
                                .execute().body();
                        baseBean.writeLog("SyncKqjOrgDataJob delete result is:" + key + "、" + result);
                        deleteIdSet.add(key);
                    }
                    List<String> list = querySupDepartmentData(key);
                    if (!CollectionUtils.isEmpty(list)) {
                        for (String xjBm : list) {
                            Map<String, String> xjBmMap = oaOrgInfoMap.get(xjBm);
                            if (CollectionUtils.isEmpty(xjBmMap)) {
                                continue;
                            }
                            String canceledTemp = xjBmMap.get("canceled");
                            if (StringUtils.isNotEmpty(canceledTemp) && StringUtils.equals(canceledTemp, "1")) {
                                if (CollectionUtils.isEmpty(deleteIdSet) || !deleteIdSet.contains(xjBm)) {
                                    String deleteUrlTemp = deleteUrl + xjBm + "?access_token=" + token;
                                    String result = HttpRequest.post(deleteUrlTemp)
                                            .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                                            .timeout(20000)
                                            .execute().body();
                                    baseBean.writeLog("SyncKqjOrgDataJob delete result is:" + xjBm + "、" + result);
                                    deleteIdSet.add(xjBm);
                                }
                            } else {
                                break;
                            }
                        }
                    }
                } else {
                    List<String> list = querySupDepartmentData(key);
                    Map<String, Object> paramMap = new HashMap<>();
                    if (!CollectionUtils.isEmpty(list)) {
                        Collections.reverse(list);
                        for (String xjBm : list) {
                            Map<String, String> xjBmMap = oaOrgInfoMap.get(xjBm);
                            if (CollectionUtils.isEmpty(xjBmMap)) {
                                continue;
                            }
                            String departmentmark = xjBmMap.get("departmentmark");
                            String canceledTemp = xjBmMap.get("canceled");
                            if (StringUtils.isNotEmpty(canceledTemp)) {
                                break;
                            }
                            if (CollectionUtils.isEmpty(addIdSet) || !addIdSet.contains(xjBm)) {
                                String supdepid = xjBmMap.get("supdepid");
                                if (StringUtils.isEmpty(supdepid) || StringUtils.equals(supdepid, "0")) {
                                    supdepid = null;
                                }
                                String showorder = xjBmMap.get("showorder");
                                if (StringUtils.isEmpty(showorder) || new BigDecimal(showorder).compareTo(new BigDecimal("1")) < 0) {
                                    showorder = "1";
                                }
                                paramMap = new HashMap<>();
                                paramMap.put("name", departmentmark);
                                paramMap.put("code", xjBm);
                                paramMap.put("parentCode", supdepid);
                                paramMap.put("sortNo", Double.parseDouble(showorder));
                                baseBean.writeLog("SyncKqjOrgDataJob add/update paramMap is:" + xjBm + "、" + paramMap);
                                String result = HttpRequest.post(addUrl)
                                        .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                                        .body(JSONObject.toJSONString(paramMap))
                                        .timeout(20000)
                                        .execute().body();
                                baseBean.writeLog("SyncKqjOrgDataJob add/update result is:" + xjBm + "、" + result);
                                addIdSet.add(xjBm);
                            }
                        }
                    }
                    if (CollectionUtils.isEmpty(addIdSet) || !addIdSet.contains(key)) {
                        String departmentmark = value.get("departmentmark");
                        String supdepid = value.get("supdepid");
                        if (StringUtils.isEmpty(supdepid) || StringUtils.equals(supdepid, "0")) {
                            supdepid = null;
                        }
                        String showorder = value.get("showorder");
                        if (StringUtils.isEmpty(showorder) || new BigDecimal(showorder).compareTo(new BigDecimal("1")) < 0) {
                            showorder = "1";
                        }
                        paramMap = new HashMap<>();
                        paramMap.put("name", departmentmark);
                        paramMap.put("code", key);
                        paramMap.put("parentCode", supdepid);
                        paramMap.put("sortNo", Double.parseDouble(showorder));
                        baseBean.writeLog("SyncKqjOrgDataJob add/update paramMap is:" + key + "、" + paramMap);
                        String result = HttpRequest.post(addUrl)
                                .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                                .body(JSONObject.toJSONString(paramMap))
                                .timeout(20000)
                                .execute().body();
                        baseBean.writeLog("SyncKqjOrgDataJob add/update result is:" + key + "、" + result);
                        addIdSet.add(key);
                    }
                }
            }
        } catch (Exception e) {
            baseBean.writeLog("SyncKqjOrgDataJob error:" + e);
        }
        baseBean.writeLog("SyncKqjOrgDataJob end.");
    }

    public List<String> querySupDepartmentData(String deptid) {
        RecordSet rs = new RecordSet();
        List<String> list = new ArrayList<String>();
        if(StringUtils.isNotBlank(deptid)){
            String sql = " select isnull(supdepid,0) as supdepid from hrmdepartment where id = "+deptid;
            rs.executeQuery(sql);
            if (rs.next()){
                String supdepid = Util.null2String(rs.getString("supdepid"));
                if(!"0".equals(supdepid)){
                    list.add(supdepid);
                    addChildDept(list,supdepid);
                }
            }
        }
        Collections.reverse(list);
        return list;
//        if(list != null && list.size() !=0){
//            Collections.reverse(list);
//            return list.stream().collect(Collectors.joining(","));
//        }else{
//            return "";
//        }
    }

    public void addChildDept(List<String> datasList, String id) {
        String sql = " select isnull(supdepid,0) as supdepid from hrmdepartment where id="+id;
        RecordSet rs = new RecordSet();
        rs.execute(sql);
        if(rs.next()){
            String supdepid = Util.null2String(rs.getString("supdepid"));
            if(!"0".equals(supdepid)){
                if(!datasList.contains(supdepid)){
                    datasList.add(supdepid);
                }
                addChildDept(datasList,supdepid);
            }
        }
    }
}
